package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import com.lagou.utils.TokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class simpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boudSql = getBoudSql(sql);

        // 3.获取预处理对象：preparedStatement


        PreparedStatement preparedStatement = connection.prepareStatement(boudSql.getSqlText());
        // 4. 设置参数
        //获取到了参数的全路径
        String paramType = mappedStatement.getParamType();
        Class<?> classByType = getClassByType(paramType);
        List<ParameterMapping> parameterMappings = boudSql.getParameterMappings();
        for (int inner = 0; inner < parameterMappings.size(); inner++) {
            ParameterMapping parameterMapping = parameterMappings.get(inner);
            String content = parameterMapping.getContent();
            Field declaredField = classByType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(inner + 1, o);
        }

        // 5. 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 6. 封装返回结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassByType(resultType);
        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int outer = 1; outer <= columnCount; outer++) {
                String columnName = metaData.getColumnName(outer);
                Object object = resultSet.getObject(columnName);
                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, object);
            }
            objects.add(o);

        }
        return (List<E>) objects;
    }

    @Override
    public void insert(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boudSql = getBoudSql(sql);

        // 3.获取预处理对象：preparedStatement


        PreparedStatement preparedStatement = connection.prepareStatement(boudSql.getSqlText());
        // 4. 设置参数
        //获取到了参数的全路径
        String paramType = mappedStatement.getParamType();
        Class<?> classByType = getClassByType(paramType);
        List<ParameterMapping> parameterMappings = boudSql.getParameterMappings();
        for (int inner = 0; inner < parameterMappings.size(); inner++) {
            ParameterMapping parameterMapping = parameterMappings.get(inner);
            String content = parameterMapping.getContent();
            Field declaredField = classByType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(inner + 1, o);
        }

        // 5. 执行sql
        preparedStatement.executeUpdate();
    }

    @Override
    public void update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boudSql = getBoudSql(sql);

        // 3.获取预处理对象：preparedStatement


        PreparedStatement preparedStatement = connection.prepareStatement(boudSql.getSqlText());
        // 4. 设置参数
        //获取到了参数的全路径
        String paramType = mappedStatement.getParamType();
        Class<?> classByType = getClassByType(paramType);
        List<ParameterMapping> parameterMappings = boudSql.getParameterMappings();
        for (int inner = 0; inner < parameterMappings.size(); inner++) {
            ParameterMapping parameterMapping = parameterMappings.get(inner);
            String content = parameterMapping.getContent();
            Field declaredField = classByType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(inner + 1, o);
        }

        // 5. 执行sql
        preparedStatement.executeUpdate();

    }

    @Override
    public void delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        String sql = mappedStatement.getSql();
        BoundSql boudSql = getBoudSql(sql);

        // 3.获取预处理对象：preparedStatement


        PreparedStatement preparedStatement = connection.prepareStatement(boudSql.getSqlText());
        // 4. 设置参数
        //获取到了参数的全路径
        String paramType = mappedStatement.getParamType();
        Class<?> classByType = getClassByType(paramType);
        List<ParameterMapping> parameterMappings = boudSql.getParameterMappings();
        for (int inner = 0; inner < parameterMappings.size(); inner++) {
            ParameterMapping parameterMapping = parameterMappings.get(inner);
            String content = parameterMapping.getContent();
            Field declaredField = classByType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(inner + 1, o);
        }

        // 5. 执行sql
        preparedStatement.executeUpdate();
    }

    private Class<?> getClassByType(String paramType) throws ClassNotFoundException {
        Class<?> aClass = Class.forName(paramType);
        return aClass;
    }

    private BoundSql getBoudSql(String sql) {
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        String parse = genericTokenParser.parse(sql);

        return new BoundSql(parse, parameterMappings);
    }
}
